//
//  HSYBaseViewController+ExportSession.m
//  高仿暴走斗图
//
//  Created by key on 16/6/13.
//  Copyright © 2016年 huangsongyao. All rights reserved.
//

#import "HSYBaseViewController+ExportSession.h"

@implementation HSYBaseViewController (ExportSession)

- (void)changeVideoToMP4:(NSURL *)videoURL withErrorBlock:(void(^)(NSError *error))errorBlock cancelledBlock:(void(^)(id x))cancelBlock completed:(void(^)(NSString *path))completed {
    
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    
    if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality]) {
        
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetLowQuality];
        CMTime audioDuration = avAsset.duration;
        Float64 audioDurationSeconds = CMTimeGetSeconds(audioDuration);
        
        // 初始化保存的路径
        NSURL *documentsDirUrl = CHANGE_VIDEO_PATH_URL(CHANGE_VIDEO_PATH);
        [self filterCacheVideoFilesByFileName:CHANGE_VIDEO_PATH_SUFFIX];
        exportSession.outputURL = [NSURL URLWithString:CHANGE_VIDEO_PATH_SUFFIX relativeToURL:documentsDirUrl];
        
        exportSession.outputFileType = AVFileTypeMPEG4;
        CMTime start = CMTimeMakeWithSeconds(1.0, CHANGE_VIDEO_FGS);                        //起始时间为：1.0秒，视频帧数为：600
        CMTime duration = CMTimeMakeWithSeconds(audioDurationSeconds, CHANGE_VIDEO_FGS);    //视频结束时间为：视频时长，视频帧数为：600
        CMTimeRange range = CMTimeRangeMake(start, duration);
        exportSession.timeRange = range;
        
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            
            switch ([exportSession status]) {
                    
                case AVAssetExportSessionStatusFailed:
                    NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
                    errorBlock(exportSession.error);
                    break;
                    
                case AVAssetExportSessionStatusCancelled:
                    
                    cancelBlock(@(AVAssetExportSessionStatusCancelled));
                    break;
                    
                case AVAssetExportSessionStatusCompleted:
                    
                    completed([[documentsDirUrl absoluteString] stringByAppendingString:CHANGE_VIDEO_PATH_SUFFIX]);
                    break;
                    
                default:
                    
                    break;
            }
        }];
    }
}


- (RACSignal *)rac_changeVideoMOVToMP4:(NSURL *)videoURL {
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
       
        [self changeVideoToMP4:videoURL withErrorBlock:^(NSError *error) {
            
            [subscriber sendError:error];
            [subscriber sendCompleted];
            
        } cancelledBlock:^(id x) {
            
            [subscriber sendNext:x];
            [subscriber sendCompleted];
            
        } completed:^(NSString *path) {
            
            [subscriber sendNext:path];
            [subscriber sendCompleted];
        }];
        return nil;
    }];
}


- (void)filterCacheVideoFilesByFileName:(NSString *)fileName {
    
    NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:CHANGE_VIDEO_PATH];
    for (NSString *name in enumerator) {
        if ([fileName isEqualToString:name]) {
            NSError *error = nil;
            NSString *path = [[NSString stringWithFormat:@"%@/", CHANGE_VIDEO_PATH] stringByAppendingString:fileName];
            BOOL isRMSuccess = [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
            if (isRMSuccess) {
                NSLog(@"success");
            }
        }
    }
}


@end
